package com.homer.commons.sscpprotocol.server.base;

import java.nio.ByteOrder;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.demux.MessageEncoder;

public abstract class AbstractMessageEncoder<T extends AbstractMessage>
  implements MessageEncoder<T>
{
  private boolean bigEndian = true;
  public final int version;

  protected AbstractMessageEncoder(int version)
  {
    this.version = version;
  }

  public void setBigEndian(boolean bigEndian) {
    this.bigEndian = bigEndian;
  }

  public void encode(IoSession session, T message, ProtocolEncoderOutput out) throws Exception
  {
    IoBuffer buf = IoBuffer.allocate(256);
    if (this.bigEndian)
      buf.order(ByteOrder.BIG_ENDIAN);
    else {
      buf.order(ByteOrder.LITTLE_ENDIAN);
    }
    buf.setAutoExpand(true);

    //buf.putInt(this.version);

    encodeMessage(session, message, buf);
    buf.flip();
    out.write(buf);
  }

  protected abstract void encodeMessage(IoSession paramIoSession, T paramT, IoBuffer paramIoBuffer);
}
